package org.pine.start.interceptor;

import com.baomidou.mybatisplus.extension.plugins.handler.MultiDataPermissionHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.statement.select.PlainSelect;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.sql.SQLException;

/**
 * 数据权限拦截器</br>
 * 如果需要使用该拦截器，需要给RoleCustomDataPermissionHandler配置监听器
 *
 * @author pine manage
 * @since 2024-09-26
 */
@Slf4j
public class MybatisPlusPermissionInterceptor extends DataPermissionInterceptor {

    public MybatisPlusPermissionInterceptor() {
        super(new RoleCustomDataPermissionHandler());
    }

    /**
     * 设置 where 条件
     *
     * @param plainSelect    查询对象
     * @param whereStatement 查询条件片段
     */
    protected void setWhere(PlainSelect plainSelect, String whereStatement) {
        if (this.getDataPermissionHandler() instanceof MultiDataPermissionHandler) {
            super.processPlainSelect(plainSelect, whereStatement);
            return;
        }

        if (this.getDataPermissionHandler() instanceof CustomDataPermissionHandler handler) {
            Expression sqlSegment = handler.getSqlSegmentWithPermission(plainSelect, whereStatement);
            if (null != sqlSegment) {
                plainSelect.setWhere(sqlSegment);
            }
        }
    }

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        super.beforeUpdate(executor, ms, parameter);
    }
}
